using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Web;
using ud_Article.Business;
using Resources;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class BlogCategoryEdit : mojoBasePage
    {
        readonly DBArticleCategory repository = new DBArticleCategory();
        private int pageId = -1;
        private int moduleId = -1;
        private int categoryID = -1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string ViewContentImage = "View.png";
        private ud_ArticleCategory category;

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            LoadPanels();
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            btnEdit.Click += btnEdit_Click;
            btnDelete.Click += btnDelete_Click;
            btnView.Click += btnView_Click;
            btnDeleteImg.Click += btnDeleteImg_Click;
            base.OnInit(e);
            SiteUtils.SetupEditor(edDescription);
        }

        void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        {
            if (category == null) { category = repository.GetOne(categoryID); }
            DeleteImageFromServer();
            divImage.Visible = false;
            repository.Update(categoryID, category.Category, category.ParentID.Value, category.SortOrder, string.Empty, category.Description);
        }


        #endregion

        private void LoadPanels()
        {
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            if (!Request.IsAuthenticated)
            {
                SiteUtils.RedirectToLoginPage(this);
                return;
            }
            SecurityHelper.DisableBrowserCache();

            LoadSettings();
            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToEditAccessDeniedPage();
            }
            
            PopulateLabels();

            if (!Page.IsPostBack)
            {
                PopulateCategories();
                PopulateControls();
            }

        }


        private void PopulateLabels()
        {
            litContentTab.Text = @"<a href='#tabContent'>" + ArticleResources.ContentTab + @"</a>";
            litDescriptionTab.Text = @"<a href='#tabDescription'>" + ArticleResources.ExcerptTab + @"</a>";

            btnDeleteImg.ImageUrl = "~/Data/SiteImages/delete.gif";
            btnDeleteImg.ToolTip = ArticleResources.ArticleDeleteLinkText;
            btnBack.Text = ArticleResources.ButtonBack;
            btnSave.Text = ArticleResources.ButtonSave;
            btnView.ImageUrl = ImageSiteRoot + "/Data/Icon16x16/" + ViewContentImage;
            btnView.ToolTip = ArticleResources.ViewCategory;
            btnView.AlternateText = ArticleResources.ViewCategory;
            btnEdit.ImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
            btnEdit.ToolTip = ArticleResources.BlogEditEntryLink;
            btnEdit.AlternateText = ArticleResources.BlogEditEntryLink;
            btnDelete.ImageUrl = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
            btnDelete.ToolTip = ArticleResources.ArticleDeleteLinkText;
            btnDelete.AlternateText = ArticleResources.ArticleDeleteLinkText;
            UIHelper.AddConfirmationDialog(btnDelete, ArticleResources.BlogDeleteCategoryWarning);
            lblTitle.Text = ArticleResources.BlogEditCategoriesLabel;
            Title = SiteUtils.FormatPageTitle(siteSettings, ArticleResources.BlogEditCategoriesLabel);
            if (Master == null) return;
            Control c = Master.FindControl("Breadcrumbs");
            if (c == null) return;
            BreadcrumbsControl crumbs = (BreadcrumbsControl)c;
            crumbs.ForceShowBreadcrumbs = true;
        }


        private void PopulateControls()
        {
            if (categoryID <= 0)
            {
                lbCategoryParent.SelectedIndex = 0;
            }
            else
            {
                ud_ArticleCategory currentCategory = repository.GetOne(categoryID);
                lbCategoryParent.Items.FindByValue(currentCategory.ParentID.ToString()).Selected = true;
                txtNewCategoryName.Text = currentCategory.Category;
                txtSortOrder.Text = currentCategory.SortOrder.ToString();
                edDescription.Text = currentCategory.Description;
            }
            if (category != null && !string.IsNullOrEmpty(category.ImageUrl))
            {
                divImage.Visible = true;
                imgView.ImageUrl = "~/" + ConfigurationManager.AppSettings["ArticleImagesFolder"] + category.ImageUrl;
            }
            else { divImage.Visible = false; }
        }

        private void PopulateCategories()
        {
            List<ud_ArticleCategory> roots = repository.GetRoot(moduleId);
            foreach (ud_ArticleCategory item in roots)
            {
                ListItem list = new ListItem
                {
                    Text = item.Category + @" (" + item.SortOrder + @")",
                    Value = item.CategoryID.ToString()
                };
                lbCategoryParent.Items.Add(list);
            }
            lbCategoryParent.Items.Remove(lbCategoryParent.Items.FindByValue(categoryID.ToString()));
            PopulateChildNode(lbCategoryParent);
            lbCategoryParent.Items.Insert(0, new ListItem(ArticleResources.ParentCategoryChoose, "0"));
        }

        private void PopulateChildNode(ListControl root)
        {
            for (int i = 0; i < root.Items.Count; i++)
            {
                List<ud_ArticleCategory> children = repository.GetChildren(int.Parse(root.Items[i].Value));
                if (children.Count <= 0) continue;
                string prefix = string.Empty;
                while (root.Items[i].Text.StartsWith("|"))
                {
                    prefix += root.Items[i].Text.Substring(0, 3);
                    root.Items[i].Text = root.Items[i].Text.Remove(0, 3);
                }
                root.Items[i].Text = prefix + root.Items[i].Text;
                int index = 1;
                foreach (ud_ArticleCategory child in children)
                {
                    if (child.CategoryID.Equals(categoryID)) continue;
                    ListItem list = new ListItem
                                        {
                                            Text = prefix + @"|--" + child.Category + @" (" + child.SortOrder + @")",
                                            Value = child.CategoryID.ToString()
                                        };
                    root.Items.Insert(root.Items.IndexOf(root.Items[i]) + index, list);
                    index++;
                }
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        void btnEdit_Click(object sender, ImageClickEventArgs e)
        {
            categoryID = Convert.ToInt32(lbCategoryParent.SelectedValue);
            WebUtils.SetupRedirect(this, SiteRoot + "/Article/EditCategory.aspx?pageid=" + pageId + "&mid=" + moduleId +
                                    "&catid=" + categoryID);
        }

        void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            categoryID = Convert.ToInt32(lbCategoryParent.SelectedValue);
            if(categoryID > 0)
            {
                repository.Delete(categoryID);
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/Article/EditCategory.aspx?pageid=" + pageId + "&mid=" + moduleId);
        }

        void btnView_Click(object sender, ImageClickEventArgs e)
        {
            categoryID = Convert.ToInt32(lbCategoryParent.SelectedValue);
            if (categoryID > 0)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/Article/ViewListByCategory.aspx?pageid=" + pageId + "&mid=" + moduleId + "&cat=" + categoryID);
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/Article/ViewList.aspx?pageid=" + pageId + "&mid=" + moduleId);
        }

        private void Save()
        {
            string fileName;
            if (!SaveImageUrl(out fileName))
            {
                return;
            }
            if (categoryID.Equals(-1))
            {
                repository.Create(moduleId, txtNewCategoryName.Text, Convert.ToInt32(lbCategoryParent.SelectedValue), Convert.ToInt32(txtSortOrder.Text), fileName, edDescription.Text);
            }
            else
            {
                repository.Update(categoryID, txtNewCategoryName.Text, Convert.ToInt32(lbCategoryParent.SelectedValue), Convert.ToInt32(txtSortOrder.Text), fileName, edDescription.Text);
            }
            WebUtils.SetupRedirect(this, SiteRoot + "/Article/EditCategory.aspx?pageid=" + pageId + "&mid=" + moduleId);
        }

        private bool SaveImageUrl(out string fileName)
        {
            String pathToApplicationsFolder
                = HttpContext.Current.Server.MapPath(
                "~/" + ConfigurationManager.AppSettings["ArticleImagesFolder"]);
            if (!Directory.Exists(pathToApplicationsFolder))
            {
                Directory.CreateDirectory(pathToApplicationsFolder);
            }
            bool flag = false;
            int width = 0;
            int height = 0;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (nuImageUrl.HasFile && nuImageUrl.ContentLength > 0)
                {

                    string fileExtension = Path.GetExtension(nuImageUrl.FileName);
                    Double fileSize = nuImageUrl.ContentLength / 1024;

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedImageFileExtensions"))
                    {
                        lblImageUrlError.Text = ArticleResources.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedImageSize"))
                    {
                        lblImageUrlError.Text = ArticleResources.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["ArticleImagesFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    System.Drawing.Image image = System.Drawing.Image.FromStream(nuImageUrl.FileContent);
                    nuImageUrl.FileContent.Close();
                    int resizeWidth;
                    int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxWidth"], out resizeWidth);
                    int resizeHeight;
                    int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxHeight"], out resizeHeight);
                    int thumbnailWidth;
                    int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxThumbnailWidth"], out thumbnailWidth);
                    int thumbnailHeight;
                    int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxThumbnailHeight"], out thumbnailHeight);
                    Utilities.ResizeImage(ref width, ref height, resizeWidth, resizeHeight, image.Width, image.Height);
                    fileName = path + guid + "_t" + fileExtension;
                    if (height != 0)
                    {
                        using (Bitmap bitmap = new Bitmap(image, width, height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    else
                    {
                        using (Bitmap bitmap = new Bitmap(image, image.Width, image.Height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    Utilities.ResizeImage(ref width, ref height, thumbnailWidth, thumbnailHeight, image.Width, image.Height);
                    fileName = path + guid + fileExtension;
                    if (height != 0)
                    {
                        using (Bitmap bitmap = new Bitmap(image, width, height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    else
                    {
                        using (Bitmap bitmap = new Bitmap(image, image.Width, image.Height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    fileName = guid + fileExtension;
                    if (!category.ImageUrl.Equals(string.Empty))
                    {
                        DeleteImageFromServer();
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                lblImageUrlError.Visible = true;
                lblImageUrlError.Text = e.Message;//"Error when upload image";
            }
            return flag;
        }

        private void DeleteImageFromServer()
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["ArticleImagesFolder"] + category.ImageUrl;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            string imageURL = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            if (File.Exists(imageURL))
            {
                File.Delete(imageURL);
            }
            if (File.Exists(thumbnailImageURL))
            {
                File.Delete(thumbnailImageURL);
            }
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            categoryID = WebUtils.ParseInt32FromQueryString("catid", categoryID);
            category = repository.GetOne(categoryID);
            edDescription.WebEditor.ToolBar = ToolBar.FullWithTemplates;
        }
    }
}
